package cn.com.cetccst.distribution.action;

import android.content.Context;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import cn.com.cetccst.distribution.business.message.EmptyMessage;
import cn.com.cetccst.distribution.business.message.EnterpriseMessage;
import cn.com.cetccst.distribution.business.message.IMessage;
import cn.com.cetccst.distribution.mqtt.DistributionMqtt;
import cn.com.cetccst.distribution.mqtt.Topics;
import cn.com.cetccst.logmanager.LogManager;

//这里需要单独一个Action吗？？？
public class InboxMessageAction {
    public static final String FIELD_NOTICE_TYPE = "noticeType";

    public static final String MESSAGE_TYPE_NOTICE = "NOTICE";

    public static void subscribeBusiness(Context context) {

        //按照协议设计消息通知应该是个单独的topic
        DistributionMqtt.get().subscribe(Topics.TOPIC_MESSAGE, new DistributionMqtt.Callback() {

            @Override
            public void onMessageArrived(String message) {
                Log.e("InboxMessageAction", "received message : " + message);
                parseMessage(context, message);
            }
        });
    }

    public static void parseMessage(Context context, String content) {
        JSONObject rootJson = null;
        try {
            rootJson = new JSONObject(content);
        } catch (JSONException e) {
            e.printStackTrace();
            new EmptyMessage().parse(context);
            return;
        }

        String msgType = rootJson.optString(FIELD_NOTICE_TYPE).toUpperCase();
        IMessage message;
        //todo add more msgtype
        switch (msgType) {
            case MESSAGE_TYPE_NOTICE:
                message = new EnterpriseMessage(rootJson);
                break;
            default:
                message = new EmptyMessage();
        }
        message.parse(context);
    }


}
